package com.aims.server.facade;

import com.aims.api.dto.AccountDTO;
import com.aims.api.dto.request.AccountListRequest;
import com.aims.api.dto.response.AccountVO;
import com.aims.api.entity.Account;
import com.aims.api.entity.query.AccountQuery;
import com.aims.common.enums.ErrorCode;
import com.aims.common.exception.BizException;
import com.aims.server.service.AccountService;
import com.aims.server.service.convert.AccountConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 账户门面服务
 * 用于适配 Controller 和 Service 之间的接口
 */
@Slf4j
@Service
public class AccountFacade {

    @Autowired
    private AccountService accountService;

    @Autowired(required = false)
    private AccountConverter accountConverter;

    // 账户类型映射
    private static final Map<Integer, String> ACCOUNT_TYPE_MAP = new HashMap<>();
    // 状态映射
    private static final Map<Integer, String> STATUS_MAP = new HashMap<>();

    static {
        ACCOUNT_TYPE_MAP.put(1, "普通账户");
        ACCOUNT_TYPE_MAP.put(2, "VIP账户");
        ACCOUNT_TYPE_MAP.put(3, "企业账户");

        STATUS_MAP.put(0, "禁用");
        STATUS_MAP.put(1, "启用");
        STATUS_MAP.put(2, "冻结");
    }

    /**
     * 获取账户列表
     */
    public List<AccountVO> getAccountList(AccountListRequest request) {
        AccountQuery query = new AccountQuery();
        query.setAccountType(request.getAccountType());
        query.setStatus(request.getStatus());

        List<Account> accounts = accountService.listByCondition(query);

        return accounts.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取账户总数
     */
    public long getAccountCount(AccountListRequest request) {
        AccountQuery query = new AccountQuery();
        query.setAccountType(request.getAccountType());
        query.setStatus(request.getStatus());

        return accountService.countByCondition(query);
    }

    /**
     * 根据ID获取账户
     */
    public AccountVO getAccountById(Long id) {
        Account account = accountService.getById(id);
        if (account == null) {
            throw new BizException(ErrorCode.DATA_NOT_FOUND, "账户不存在");
        }
        return convertToVO(account);
    }

    /**
     * 创建账户
     */
    public Long createAccount(AccountDTO accountDTO) {
        Account account = convertToEntity(accountDTO);
        account.setCreateTime(LocalDateTime.now());
        account.setUpdateTime(LocalDateTime.now());
        account.setDeleted(0);
        account.setVersion(0);

        return accountService.create(account);
    }

    /**
     * 更新账户
     */
    public void updateAccount(AccountDTO accountDTO) {
        if (accountDTO.getId() == null) {
            throw new BizException(ErrorCode.BAD_REQUEST, "账户ID不能为空");
        }

        Account existingAccount = accountService.getById(accountDTO.getId());
        if (existingAccount == null) {
            throw new BizException(ErrorCode.DATA_NOT_FOUND, "账户不存在");
        }

        Account account = convertToEntity(accountDTO);
        account.setUpdateTime(LocalDateTime.now());

        int result = accountService.updateSelectiveById(account);
        if (result == 0) {
            throw new BizException(ErrorCode.BUSINESS_ERROR, "更新账户失败");
        }
    }

    /**
     * 删除账户
     */
    public void deleteAccount(Long id) {
        Account existingAccount = accountService.getById(id);
        if (existingAccount == null) {
            throw new BizException(ErrorCode.DATA_NOT_FOUND, "账户不存在");
        }

        int result = accountService.deleteById(id);
        if (result == 0) {
            throw new BizException(ErrorCode.BUSINESS_ERROR, "删除账户失败");
        }
    }

    /**
     * 转换为 VO
     */
    private AccountVO convertToVO(Account account) {
        if (account == null) {
            return null;
        }

        AccountVO vo = new AccountVO();
        BeanUtils.copyProperties(account, vo);

        // 设置类型名称
        vo.setAccountTypeName(ACCOUNT_TYPE_MAP.getOrDefault(account.getAccountType(), "未知"));
        // 设置状态名称
        vo.setStatusName(STATUS_MAP.getOrDefault(account.getStatus(), "未知"));
        // 计算可用余额
        BigDecimal availableBalance = account.getBalance().subtract(
                account.getFrozenAmount() != null ? account.getFrozenAmount() : BigDecimal.ZERO
        );
        vo.setAvailableBalance(availableBalance);

        return vo;
    }

    /**
     * 转换为 Entity
     */
    private Account convertToEntity(AccountDTO dto) {
        if (dto == null) {
            return null;
        }

        Account account = new Account();
        BeanUtils.copyProperties(dto, account);
        return account;
    }
}